const { mysql: config } = require('../config')
const { mysql } = require('../qcloud')

module.exports = async (ctx) => {
  const { bookIsbn, openId } = ctx.request.query
  const DB = mysql
  // const DB = require('knex')({
  //   client: 'mysql',
  //   connection: {
  //     host: config.host,
  //     port: config.port,
  //     user: config.user,
  //     password: config.pass,
  //     database: config.db,
  //     charset: config.char,
  //     multipleStatements: true
  //   }
  // })
	// select comments.*, cSessionInfo.user_info from comments join cSessionInfo on comments.open_id = cSessionInfo.open_id where book_isbn = '9787115437303'\G;
  try {
    let comment = []
		let mysqlSelect = DB('comments')
			.select('comments.*', 'cSessionInfo.user_info')
      .join('cSessionInfo', 'comments.open_id', 'cSessionInfo.open_id')
      .orderBy('id', 'desc')
    if (bookIsbn) {
      comment = await mysqlSelect.where('book_isbn', bookIsbn)
    } else if (openId) {
      comment = await mysqlSelect.where('comments.open_id', openId)
    }
    ctx.state.data = {
			msg: '查询成功',
			commentList: comment.map(item => {
				return {
					...item,
					user_info: {
						nickName: JSON.parse(item.user_info).nickName,
						avatar: JSON.parse(item.user_info).avatarUrl
					}
				}
			})
    }
  } catch (e) {
    ctx.state = {
      code: -1,
      data: {
        msg: '查询失败:' + e.sqlMessage
      }
    }
  }

}
